package com.zkk.dao.impl;

import com.zkk.dao.StudentDao;
import com.zkk.pojo.Student;
import com.zkk.utils.DruidUtil;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class StudentDaoImpl implements StudentDao {
    private JdbcTemplate jdbcTemplate = new JdbcTemplate(DruidUtil.getDataSource());
    @Override
    public List<Student> findAll() {
        List<Student> query = jdbcTemplate.query("select * from student", new BeanPropertyRowMapper<>(Student.class));
        return query;
    }

    @Override
    public Student add(Student student) {
        int update = jdbcTemplate.update("insert into  student values (null,?,?,?,?)", student.getName(), student.getSex(), student.getAge(), student.getNative_pl());
        return student;
    }

    @Override
    public int deleteById(int sid) {
        int update = jdbcTemplate.update("delete from student where sid=?", sid);
        return update;
    }

    @Override
    public Student selectById(int sid) {
        List<Student> query = jdbcTemplate.query("select * from student where sid=?", new BeanPropertyRowMapper<>(Student.class),sid);
        if(query!=null && query.size()==1){
            return query.get(0);
        }
        return null;
    }

    @Override
    public int update(Student student) {
        int update = jdbcTemplate.update("update student set name = ?,sex = ?,age = ?,native_pl = ? where sid=?" , student.getName(), student.getSex(), student.getAge(), student.getNative_pl(),student.getSid());
        return update;
    }


    @Override
    public List<Student> findAll(int i, int pageSize) {
        List<Student> query = jdbcTemplate.query("select * from student limit ?,? ", new BeanPropertyRowMapper<>(Student.class), i, pageSize);
        return query;
    }

    @Override
    public int count() {
        Integer count = jdbcTemplate.queryForObject("select count(1) from student", Integer.class);
        return count;
    }

    @Override
    public List<Student> findAll(int i, int pageSize, String username) {
        List<Student> query = jdbcTemplate.query("select * from student where name like ? limit ?,?", new BeanPropertyRowMapper<>(Student.class),"%"+username+"%",i,pageSize);
        return query;
    }

    @Override
    public int count(String username) {
        Integer integer = jdbcTemplate.queryForObject("select count(*) from student where name like ?", Integer.class, "%"+username+"%");
        return integer;
    }
}
